<template>
  <div class="parent">
    <!-- 页面名称 -->
    <div class="header">
      <span>字典类别维护</span>
    </div>

    <!-- 内容 -->
    <el-container class="body">
      <el-main class="mainmain">
        <!-- 新增按钮及查询 -->
        <div class="firsthe">
          <el-button
            type="primary"
            class="add"
            pageData.formData="{};"
            @click="
              (dialogFormVisible = true),
                (pageData.isAdd = true),
                (pageData.formData = {})
            "
            >新增</el-button
          >
          <!-- 弹框内容 -->
          <el-dialog
            :width="500"
            v-model="dialogFormVisible"
            :title="pageData.isAdd ? '新增字典分类' : '编辑字典分类'"
            :close-on-click-modal="false"
            destroy-on-close
            @close="onHandleCancel"
          >
            <el-form
              ref="dicFrom"
              :model="pageData.formData"
              :rules="pageData.formRules"
              label-width="100px"
              status-icon
              :isAdd="pageData.isAdd"
            >
              <el-form-item
                label="类别编号："
                :label-width="formLabelWidth"
                prop="fDdcCode"
              >
                <el-input
                  v-model="pageData.formData.fDdcCode"
                  placeholder="请输入类别编号"
                  :disabled="!pageData.isAdd"
                />
              </el-form-item>
              <el-form-item
                label="类别名称："
                :label-width="formLabelWidth"
                prop="fDdcName"
              >
                <el-input
                  v-model="pageData.formData.fDdcName"
                  placeholder="请输入字典类别名称"
                />
              </el-form-item>
              <el-form-item label="录入人员：" :label-width="formLabelWidth">
                <el-input
                  v-model="pageData.formData.createName"
                  autocomplete="off"
                  :disabled="!pageData.isAdd || pageData.isAdd"
                  placeholder="自动填充"
                />
              </el-form-item>
              <el-form-item label="录入时间：" :label-width="formLabelWidth">
                <el-input
                  placeholder="自动填充"
                  v-model="pageData.formData.fCreatorTime"
                  autocomplete="off"
                  :disabled="!pageData.isAdd || pageData.isAdd"
                />
              </el-form-item>
              <el-form-item label="备注：" :label-width="formLabelWidth">
                <el-input
                  v-model="pageData.formData.fRemark"
                  autocomplete="off"
                />
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="onHandleCancel">取消</el-button>
                <el-button type="primary" @click="onHandleSure">
                  提交
                </el-button>
              </span>
            </template>
          </el-dialog>
          <!-- 弹框内容结束 -->

          <div class="search">
            <el-input
              v-model="pageData.queryParams.fDdcCode"
              placeholder="请输入类别编号"
              clearable
              ><template #prepend>类别编号</template>
            </el-input>

            <el-input
              v-model="pageData.queryParams.fDdcName"
              placeholder="请输入类别名称"
              clearable
              ><template #prepend>类别名称</template>
            </el-input>

            <el-button type="primary" plain @click="onHandleSearch"
              >搜索</el-button
            >
            <el-button type="warning" plain @click="onHandleReset"
              >重置</el-button
            >
          </div>
        </div>
        <!-- 主体表格 -->
        <el-table
          row-key="fId"
          highlight-current-row
          :data="pageData.tableParams.tableData"
          v-loading="pageData.tableParams.tableLoading"
          style="width: 100%"
          border
        >
          <el-table-column
            fixed
            prop="fDdcCode"
            label="类别编号"
            min-width="120"
          />
          <el-table-column prop="fDdcName" label="类别名称" min-width="120" />
          <el-table-column prop="createName" label="录入人员" min-width="120" />
          <el-table-column
            prop="fCreatorTime"
            label="录入时间"
            min-width="160"
          />
          <el-table-column prop="fState" label="状态">
            <template #="v">
              <span>{{
                v.row.fState == 0
                  ? "草稿"
                  : v.row.fState == 10
                  ? "审核中"
                  : v.row.fState == 20
                  ? "作废/删除"
                  : "审核通过"
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="fRemark" label="备注" width="600" />
          <el-table-column fixed="right" label="操作" width="120">
            <template #default="{ row }">
              <el-button
                link
                type="primary"
                size="small"
                @click="onHandleEdit(row)"
                >编辑</el-button
              >
              <el-button
                link
                type="primary"
                size="small"
                @click="onHandleDel(row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页查询 -->
        <el-col :span="24">
          <el-pagination
            style="margin-top: 20px"
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="pageData.tableParams.pageSizeOptions"
            :current-page="pageData.queryParams.page"
            :page-size="pageData.queryParams.pageSize"
            :total="pageData.tableParams.totalCount"
            @current-change="onHandleCurrentChange"
            @size-change="onHandleSizeChange"
          >
          </el-pagination>
        </el-col>
      </el-main>
    </el-container>
  </div>
</template>
<script>
import { reactive, ref, nextTick, onMounted, inject } from "vue";
import {
  query_zdcategory,
  add_zdcategory,
  delete_zdcategory,
  update_zdcategory,
} from "@/api/basic/zdcategory";
import { ElLoading, ElMessage, ElMessageBox } from "element-plus";
import utils from "@/common/utils";

export default {
  props: {
    modifyObj: { type: Object, required: true },
    isAdd: { type: Boolean, required: true, default: false },
  },
  setup(props, context) {
    onMounted(() => {
      pageData.formData = {
        fAuditUserId: "",
        fAuditorTime: "",
        fBookCode: "",
        fCreateUserId: "",
        fCreatorTime: "",
        fDdcCode: "",
        fDdcManagerId: "",
        fDdcName: "",
        fId: "",
        fLastModifyTime: "",
        fLastModifyUserId: "",
        fRemark: "",
        fState: "",
      };
      nextTick(getTableData);
      // if (!props.isAdd) {
      //   getData(props.modifyObj);
      // }
    });
    // 刷新
    const reload = inject("reload");
    const pageData = reactive({
      treeParams: {
        props: {
          label: "fDdcName",
          children: "children",
          isLeaf: "isleaf",
        },
        defaultExpKeys: [],
        currentNode: {},
      },
      currentRow: {},
      editDialogTitle: "新增字典类别",
      // editDialogVisible: false,
      isAdd: true,

      formData: {},
      formRules: {
        fDdcCode: [
          { required: true, message: "请输入字典类别编号", trigger: "blur" },
        ],
        fDdcName: [
          { required: true, message: "请输入字典类别名称", trigger: "blur" },
        ],
        fDdCode: [
          { required: true, message: "请输入字典编号", trigger: "blur" },
        ],
        fDdName: [
          { required: true, message: "请输入字典名称", trigger: "blur" },
        ],
      },
      queryParams: {
        fDdcCode: "",
        fDdcName: "",
        page: 1,
        pageSize: 10,
      },
      tableParams: {
        tableLoading: false,
        tableHeight: 0,
        pageSizeOptions: ["10", "15", "30", "50", "100", "200"],
        totalCount: 0,
        tableData: [],
      },
      selectRows: [],
    });

    // 树
    // const classTree = ref();
    // const treeLoad = (node, resolve) => {
    //   const flag = node.level === 0;
    //   const classid = flag ? "" : node.data.fId;
    //   query_zdcategory(classid)
    //     .then((ret) => {
    //       if (flag && ret.length > 0) {
    //         pageData.treeParams.defaultExpKeys = [ret[0].fclassid];
    //       }
    //       resolve(ret);
    //     })
    //     .catch((error) => {
    //       ElMessage.error(error.message || "请求出错");
    //     });
    // };

    // 获取字典类别信息
    const getTableData = () => {
      pageData.currentRow = {};
      pageData.tableParams.tableLoading = true;
      query_zdcategory(pageData.queryParams) //获取字典类别接口
        .then((res) => {
          console.log("hahahahahahah", res);
          pageData.tableParams.tableData = res.list;
          pageData.tableParams.totalCount = res.list.length;
          pageData.tableParams.tableLoading = false;
        })
        .catch(() => {
          pageData.tableParams.tableLoading = false;
        });
    };

    // 分页查询
    const onHandleCurrentChange = (e) => {
      pageData.queryParams.page = e;
      console.log("e", e);
      getTableData();
    };
    const onHandleSizeChange = (e) => {
      pageData.queryParams.page = 1;
      pageData.queryParams.pageSize = e;
      console.log("e2", e);

      getTableData();
    };

    const dialogFormVisible = ref(false);
    const dicFrom = ref();

    // 新增字典类别
    const onHandleSure = () => {
      dicFrom.value?.validate((valid) => {
        if (valid) {
          if (pageData.isAdd) {
            add_zdcategory(pageData.formData)
              .then((res) => {
                if (res.msg === "该编号已经存在") {
                  ElMessage.error("该编号已经存在,请重新输入");

                  // dialogFormVisible.value = false;
                } else if (res.msg === "该名称已经存在") {
                  ElMessage.error("该名称已经存在,请重新输入");
                } else {
                  dialogFormVisible.value = false;
                  getTableData();
                }
              })
              .catch((error) => {
                ElMessage.error(error.message || "请求出错");
              });
          } else {
            pageData.formData.fCreatorTime = new Date(
              pageData.formData.fCreatorTime
            );

            update_zdcategory(pageData.formData)
              .then(() => {
                dialogFormVisible.value = false;
                getTableData();
                // 刷新页面
                reload();
              })
              .catch((error) => {
                ElMessage.error(error.message || "请求出错");
              });
          }
        }
      });
    };
    // 取消新增
    const onHandleCancel = () => {
      // console.log('dicForm.value',dicForm.value)
      dicFrom.value?.resetFields();
      // context.emit("cancel");
      dialogFormVisible.value = false;
    };

    // 修改字典类别
    const onHandleEdit = (row) => {
      pageData.currentRow = {};
      // pageData.currentRow = row;
      pageData.formData = row;
      // console.log("row", row);
      // console.log("pageData.editDialogTitle", pageData.editDialogTitle);
      dialogFormVisible.value = true;
      pageData.isAdd = false;

      // getTableData();
    };

    // 删除字典类别
    const onHandleDel = (row) => {
      console.log("shanchu row", row);
      pageData.currentRow = {};
      if (utils.isEmpty(row.fId)) {
        ElMessage.warning("请选中需要操作的数据行");
        return;
      }
      ElMessageBox.confirm("是否确定删除该字典类别", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then((res) => {
          delete_zdcategory(row.fId)
            .then((res) => {
              ElMessage({
                type: "success",
                message: "删除成功",
              });
              getTableData();
            })
            .catch((error) => {
              ElMessage.error(error.message || "请求出错");
            });
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "删除失败",
          });
          return;
        });
    };

    // 搜索
    const onHandleSearch = () => {
      getTableData();
    };
    const onHandleReset = () => {
      pageData.queryParams.fDdcCode = "";
      pageData.queryParams.fDdcName = "";
      getTableData();
    };

    return {
      pageData,
      getTableData,
      dicFrom,
      dialogFormVisible,
      onHandleSure,
      onHandleCancel,
      onHandleCurrentChange,
      onHandleSizeChange,
      onHandleEdit,
      onHandleDel,
      onHandleSearch,
      onHandleReset,
    };
  },
};
</script>
<style lang="scss" scoped>
.parent {
  padding: 0;
  margin: 0;
  // 头部页面名称
  .header {
    width: 100%;
    // height: 50px;
    background-color: white;
    user-select: none;
    // margin: auto;
    // padding-left: 20px;
    text-align: left;
    span {
      line-height: 50px;
      font-size: 18px;
      font-weight: 700;
      text-align: left;
      margin-left: 20px;
    }
  }
  .body {
    margin-top: 20px;
    background-color: white;
    height: 77vh;
    // 树形下拉框
    .mainaside {
      background-color: rgb(230, 240, 250);
      border-right: 1px solid #ccc;
      .user_tree {
        .el-tree {
          border-bottom: 1px solid #ddd;
        }
      }
    }
    // 内容表格
    .mainmain {
      width: 100%;
      .firsthe {
        width: 100%;
        display: flex;
        justify-content: space-between;
        margin-bottom: 20px;

        .add {
          margin-right: 20px;
        }
        // justify-content: space-between;

        .search {
          // width: 250px;
          display: flex;
          align-items: center;
          user-select: none;

          .el-input {
            margin-right: 20px;
          }
        }
      }
    }
  }
}
</style>

<style>
.el-dialog {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  user-select: none;
}

.el-dialog .el-dialog__body {
  flex: 1;
  overflow: auto;
}
.el-dialog .el-dialog__header {
  padding: 20px 0;
  padding-left: 20px;
  margin: 0;
  /* padding-bottom: 10px; */
  /* margin-right: 16px; */
  word-break: break-all;
  border-bottom: 1px solid #ddd;
  text-align: left;
  /* margin-left: 20px; */
}

.el-select {
  width: 100%;
  border: none;
  border-radius: 0;
}
.el-select .el-option {
  width: 100%;
  border: none;
  border-radius: 0;
}
.el-input-group__prepend {
  padding: 0 10px;
}
</style>
